<?php
/**
 * Notes:
 * Created by PhpStorm.
 * Author: TS
 * Date: 2019/10/12
 * Time: 10:40
 */

namespace app\index\controller;

use app\model\Chat as ChatModel;
use app\model\ChatList;
use app\model\Friends as FriendMode;
use app\model\GroupChatList;
use app\model\Users;
use app\validate\ChatValidate;

class Chat
{
    /**
     *
     * @return false|string
     */
    public function getChat(){
        if(request()->isPost()){
            $user_id = getNowUserId();
            $target_id = input('post.target_id');
            if(!checkNull($target_id)) return res(0,MSG_PARAM);
            $ChatModel = new ChatModel();
            $my = $ChatModel->getChatByUser($user_id,$target_id);
            $friend = $ChatModel->getChatByUser($target_id,$user_id);

            $data = array_merge($my,$friend);
            $flag = array();
            foreach($data as $v){
                $flag[] = $v['chat_time'];
            }
            array_multisort($flag, SORT_ASC, $data);
            return res(1,'',$data);
        }
        return res(0,MSG_NOT_POST);
    }

    /**
     * 向好友发送消息
     * @return false|string
     */
    public function sendUserChat(){
        if(request()->isPost()){
            $chat_target = getNowUserId();//获取当前登录用户
            $data = request()->only('chat_content,chat_mod');
            $chat_mod = $data['chat_mod'];
            $friend_id = input('post.friend_id');
            $data["user_id"] = $friend_id;
            $ChatValidate = new ChatValidate();
            //验证信息
            if(!$ChatValidate->check($data)) return res(0,$ChatValidate->getError());
            $FriendMode = new FriendMode();
            //核查是否有该好友
            if(!$FriendMode->check($chat_target,$data["user_id"])) return res(0,'您还未添加该用户为好友');
            $data["chat_target"] = $chat_target;
            $data['chat_status'] = 1;
//            $data['chat_mod'] = 1;
            $data['chat_time'] = time();
            $ChatModel = new ChatModel();
            //开启事务
            $ChatModel->startTrans();
            //发送消息
            $chat_res = $ChatModel->addChat($data);
            if(!$chat_res){
                $ChatModel->rollback();
                return res(1,' 发送失败');
            }

            $ChatListMode = new ChatList();
            //开启事务
            $ChatListMode -> startTrans();
            $chat_list = [
                'type' => 1,
                'user_id' => $friend_id,
                'chat_target' => $chat_target,
                'chat_num' => '1',
                'chat_mod' => $chat_mod,
                'chat_content' => $data['chat_content'],
                'push_time' => time()
            ];
            //核查我放推送消息列表
            $checkPush = $ChatListMode->checkPush($friend_id,$chat_target);
            //核查对方推送消息列表
            $checkTarget = $ChatListMode->checkPush($chat_target,$friend_id);

            $target_push_response = null;
            //如果我方推送列表不存在，则添加
            if($checkPush == null) {
                $chat_list['chat_num'] = 0;
                $checkMyAdd = $ChatListMode->add($chat_list);
                if(!$checkMyAdd){
                    //添加失败，回滚数据
                    $ChatModel->rollback();
                    $ChatListMode->rollback();
                    return res(0,'发送失败');
                }
                //清空，作为标识
                $checkPush == null;
            }
            //如果对方推送列表不存在则添加
            if($checkTarget == null){
                $chat_list['user_id'] = $chat_target;
                $chat_list['chat_target'] = $friend_id;
                $checkTargetAdd = $ChatListMode->add($chat_list);
                if(!$checkTargetAdd){
                    //添加失败，回滚数据
                    $ChatModel->rollback();
                    $ChatListMode->rollback();
                    return res(0,'发送失败');
                }
                $target_push_response = $checkTargetAdd;
                //清空，作为标识
                $checkTarget = null;
            }
            //更新推送消息列表数据集
            $update_data = [
                'chat_content' => $data['chat_content'],
                'chat_mod' => $chat_mod,
                'push_time' => time(),
            ];
            //如果标识为空，意味着上面未添加数据，下面就要更新数据
            if($checkPush != null) {
                $chat_data = $checkPush;
                //更新我放消息未读数量
                $update_data['chat_num'] = $chat_data['chat_num'] + 1;
                $update_res = $ChatListMode->edit($chat_data['chat_list_id'], $update_data);
                //更新失败数据回滚
                if (!$update_res) {
                    $ChatModel->rollback();
                    $ChatListMode->rollback();
                    return res(0, '发送失败');

                }
            }
            //如果标识为空，意味着上面未添加数据，下面就要更新数据
            /*if($checkTarget != null) {
                $target_id = $checkTarget['chat_list_id'];
                //更新对方消息未读数量
                $update_data['chat_num'] = $checkTarget['chat_num'] + 1;
                $target_res = $ChatListMode->edit($target_id, $update_data);
                //更新失败数据回滚
                if (!$target_res) {
                    $ChatModel->rollback();
                    $ChatListMode->rollback();
                    return res(0,'发送失败');
                }


            }*/
            $target_push_response = $ChatListMode->getPushAndUser($chat_target,$friend_id);
            //以上操作皆成功，提交数据
            $ChatModel->commit();
            $ChatListMode->commit();
            $res_data = [
                'chat' => $chat_res,
                'push' => $target_push_response
            ];
            return res(1,'发送成功',$res_data);
        }
        return res(0,MSG_NOT_POST);
    }

    /**
     * 向群聊发送消息
     * @return false|string
     */
    public function sendGroupChat(){
        if(request()->isPost()){

            $user_id = getNowUserId();
            $data = request()->only('chat_content,chat_target');
            $ChatValidate = new ChatValidate();
            if(!$ChatValidate->scene('sendGroupChat')->check($data)) return res(0,$ChatValidate->getError());
            $GroupChatListMode = new GroupChatList();
            if($GroupChatListMode->checkByUser($user_id,$data['chat_target']) == 0) return res(0,'您还未加入群聊');
            $data["user_id"] = $user_id;
            $data['chat_status'] = 2;
            $data['chat_mod'] = 1;
            $data['chat_time'] = time();
            $ChatModel = new ChatModel();
            if($ChatModel->addChat($data)){
                return res(1,'发送成功');
            }
            return res(0,'发送失败');
        }
        return res(0,MSG_NOT_POST);
    }
    public function sendFileChat(){

    }

    /**
     * 撤回消息
     * @return false|string
     */
    public function recallChat(){
        if (request()->isPost()){
            $chat_id = input('post.chat_id');
            if(!checkNull($chat_id)) return res(0,MSG_NOT_KEY);
            $ChatModel = new ChatModel();
            if($ChatModel->check($chat_id) == 0) return res(0,'无该消息记录');
            $chat = $ChatModel->getById($chat_id);
            $user_id = getNowUserId();
            if($chat["chat_target"] != $user_id) return res(0,'只能撤回自己发出的消息');
            $chatTime = $chat["chat_time"];
            $now = time();
            $gapTime = ($now - strtotime($chatTime)) / 60;
            if($gapTime > 2){
                return res(0,"该消息发出已超两分钟，无法撤回");
            }
            $delResult = $ChatModel->del($chat_id);
            if($delResult) {
                return res(1, '撤回成功');
            }
            return res(0,'撤回失败');
        }
        return res(0,MSG_NOT_POST);
    }

    public function readChat(){
        if(request()->isPost()){
            $chat_list_id = input('post.chat_list_id');
            $chatUpdata = [
                'chat_num' => 0
            ];
//            $res = ChatList::edit($chatUpdata,$chat_list_id);

            if(ChatList::edit($chat_list_id,$chatUpdata)){

                return res(1,MSG_SUCCESS);
            }
            return res(0,MSG_FAIL);
        }
        return res(0,MSG_NOT_POST);
    }
    /**
     * 获取消息列表
     * @return false|string
     */
    public function getChatList(){

        if(request()->isPost()){
            $user_id = getNowUserId();
            $ChatListModel = new ChatList();
            $UserChatList = $ChatListModel->getByUser($user_id);
            $res_data = $UserChatList;
            /*foreach ($UserChatList as $item){
                $res_data["chat_list_id_" . $item["chat_list_id"]] = $item;
            }*/

            return res(1,'',$res_data);
        }
        return res(0,MSG_NOT_POST);
    }


}